/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.google.gson.Gson;
import com.vng.zing.survey.memcached.SurveyCache;
import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.Response;
import com.vng.zing.survey.thrift.model.Error;

import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.model.AnswerDetail;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.model.RenderModel;
import com.vng.zing.survey.model.ResponeDetail;
import com.vng.zing.survey.thrift.model.ListShortReponse;
import com.vng.zing.survey.thrift.model.ShortReponse;
import com.vng.zing.survey.thrift.model.UserType;
import com.vng.zing.survey.utility.Utility;
import java.util.Map;

/**
 *
 * @author namhh
 */
public class ResponseDetailController extends BaseController {

    private static UserType userType = UserType.ADMIN;

    @Override
    public String render(HttpServletRequest req, HttpServletResponse resp) throws IOException, Exception {
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();
        if (req.getParameter("id") == null) {
            return showError("Không tìm thấy khảo sát yêu cầu!");
        }

        dic.setVariable("HEADER", CommonModel.getHeader(TemplateDictionary.create(), "Phản hồi chi tiết"));
        dic.setVariable("FOOTER", CommonModel.getFooter(TemplateDictionary.create()));
        Integer idSurvey = Integer.parseInt(req.getParameter("id"));
        Map mapUser = checkMember(req, userType);
        if (mapUser.containsValue(ErrorType.FAIL) || mapUser.containsValue(ErrorType.ERROR_SYSTEM)) {
            return CommonModel.getError(dic, (String) mapUser.get("msg"));
        }
        int idUser = (int) mapUser.get("msg");
        boolean isAdmin = (boolean) mapUser.get("admin");
        if (!isAdmin) {
            return CommonModel.getError(dic, "Bạn không phải admin");

        }
        SurveyClient surveyClient = SurveyClient.getInstance();
        ListShortReponse listShortReponse = surveyClient.getListShortResPonse(idSurvey, CommonModel.OFFSET);
        List<ShortReponse> shortReponses = listShortReponse.getListshortResponse();

        DateFormat df = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
        Date date;
        int page = (int) Math.floor(listShortReponse.getCount() / CommonModel.OFFSET);
        SurveyItem surveyItem = surveyClient.getSurvey(idSurvey).getSurveyItem();

        dic.setVariable("IDSURVEY", String.format("%s", idSurvey));
        TemplateDataDictionary dicResponse = TemplateDictionary.create();

        for (int i = 0; i < shortReponses.size(); i++) {
            ShortReponse response = shortReponses.get(i);
            TemplateDataDictionary sliceResponse = dicResponse.addSection("SLICE_RESPONSES");
            sliceResponse.setVariable("NUMBER", String.format("%s", i + 1));
            sliceResponse.setVariable("USER", String.format("%s", response.getDisplayName()));
            sliceResponse.setVariable("IDUSER", String.format("%s", response.getIdUser()));
            sliceResponse.setVariable("DATA", response.getData());

            date = new Date((long) response.getTimeResponse() * 1000L);
            sliceResponse.setVariable("TIMERESPONSE", df.format(date));

        }

        if (page > 0) {
            TemplateDataDictionary dicPage = TemplateDictionary.create();
            dicPage.setVariable("COUNT", String.format("%s", page + 1));
            dicPage.setVariable("OFFSET", String.format("%s", CommonModel.OFFSET));
            dicPage.setVariable("NAME", "paging_res");

            String paging = CommonModel.getPaging(dicPage);
            dic.setVariable("PAGE", paging);
        }

        String table = CommonModel.getResponseTable(dicResponse);
        dic.setVariable("TABLE", table);
        dic.setVariable("BACKLINK", "stat?id=" + idSurvey);
        Template template = RenderModel.getCTemplate("responsedetail");
        content = template.renderToString(dic);

        return content;
    }

    private String getResponseDetailBy(SurveyItem surveyItem, Response response) {
        String result = "";
        ResponeDetail detail = new ResponeDetail();
        detail.setTitle(surveyItem.getTitle());
        List<AnswerItem> listAnswers = response.getAnswers();
        List<Question> listQuestion = surveyItem.getQuestions();
        List<AnswerDetail> listAnswerDetail = new ArrayList<AnswerDetail>();
        AnswerDetail answerDetail;

        for (Question question : listQuestion) {
            AnswerItem answerItem = Utility.getAnswerItemById(question.getIdQues(), listAnswers);
            List<String> choice = new ArrayList<String>();
            List<String> answer = new ArrayList<String>();

            if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.SINGLE_LINE) {
                if (answerItem == null) {
                    answer.add("");
                } else {
                    answer.add(answerItem.getAnswer());
                }
                choice.add("");
            } else {
                if (answerItem == null) {
                    for (int i = 0; i < question.getChoices().size(); i++) {
                        answer.add("0");
                    }
                } else {
                    answer = Arrays.asList(answerItem.getAnswer().split(","));
                }
                choice = question.getChoices();
//                if (choice.size() > answer.size()) {
//                    do {
//                        answer.add("0");
//                    } while (choice.size() > answer.size());
//
//                } else if (choice.size() < answer.size()) {
//                    do {
//                        answer.remove(answer.size() - 1);
//                    } while (choice.size() < answer.size());
//
//                }

            }

            answerDetail = new AnswerDetail(question.getTitleQues(), question.require, question.getType(), choice, answer);

            listAnswerDetail.add(answerDetail);
        }
        Gson gson = new Gson();
        detail.setAnswers(listAnswerDetail);
        System.out.println(gson.toJson(detail));
        return gson.toJson(detail);
    }

    Question getQuestionBy(SurveyItem surveyItem, int idQuestion) {
        for (Question question : surveyItem.getQuestions()) {
            if (question.getIdQues() == idQuestion) {
                return question;
            }
        }
        return null;
    }

}
